<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();
checkFunc(5);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;

display_header();

$default_search_start_day = date('Y-m-01');
$start_time = $_GET['start'] ?? null;
$end_time   = $_GET['end']   ?? null;
if(!$start_time) $start_time = null;
if(!$end_time) $end_time = null;
if($start_time !== null) $start_time = strtotime($start_time.' 00:00:00');
if($end_time !== null) $end_time   = strtotime($end_time.' 23:59:59');
if($start_time === null) $start_time = strtotime($default_search_start_day.' 00:00:00');
if($end_time === null) $end_time = strtotime($today.'23:59:59');
$search_start_day = date('Y-m-d', $start_time);
$search_end_day   = date('Y-m-d', $end_time);

$total = $DB->count('exchangerecords');
$page = $_GET['page'] ?? 1;
if($page < 1) $page = 1;
$pagesize = 20;
$total_page = ceil($total / $pagesize);
if($page > $total_page) $page = $total_page;
$start = ($page - 1) * $pagesize;

$all_records = $DB->select('exchangerecords', '*', [
    'ORDER' => ['id'=>'DESC'],
    'LIMIT' => [$start, $pagesize],
]);

$logistics = [1 => '顺丰', 2 => 'EMS', 3 => '邮政包裹', 4 => '百世汇通', 5 => '申通', 6 => '中通', 7 => '圆通', 8 => '国通', 9 => '韵达', 10 => '天天', 11 => '优速', 12 => '京东', 13 => '宅急送'];

if($action) {
if ($action == 'delivery') {
        checkFunc(5, '权限不足，无法操作');
        $method = $_POST['method'] ?? null;
        $aid = $_POST['record_id'] ?? 0;
        $logistics_company = $_POST['logistics'] ?? 0;
        $logistics_num = trim($_POST['logistics_num']);
        if (!$aid) $error = '无效的商品ID';
        else if (!$logistics) $error = '请选择物流公司';
        else {
            if ($method == 'edit'){
                $data = ['deliverTime' => time(),'logistics' => $logistics_company,'logistics_num' => $logistics_num];
                $success = '修改成功';
            }else{
                $data = ['status'=>1,'deliverTime' => time(),'logistics' => $logistics_company,'logistics_num' => $logistics_num];
                $success = '发货成功';
            }
            $DB->update('exchangerecords', $data, ['id' => $aid]);
            operate_log('exchangerecords', 'delivery', ['商品ID' => $aid,'物流ID' => $logistics_company,'物流单号' => $logistics_num]);
        }
    }
    else {
        $error = '无效的操作';
    }
    goExit('exchange_record.php?success=' . $success . '&error=' . $error);
}
?>

<style>
    #logtable {font-size:12px;}
    #logtable tr td {font-size:12px;}
</style>

<section class="content">
    <?php if($error) : ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <span><?php echo $error; ?></span>
        </div>
    <?php endif ?>
    <?php if($success) : ?>
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> 成功</h4>
            <?php echo $success; ?>
        </div>
    <?php endif ?>


    <div class="box box-warning">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-search"></i> 结果筛选</h3>
            <?php if($start_time || $logaction) { ?>
                <div style="display:inline-block;margin-left:30px;" class="filter_box">
                    当前筛选条件
                    <?php
                    if($start_time && $end_time) {
                        echo '<div>时间段:　<strong>' . date('Y-m-d', $start_time) . ' ~ ' . date('Y-m-d', $end_time) . '</strong>';
                        echo '<span class="badge bg-red" onclick="filter_go(\'time\');">X</span></div>';
                    }
                    if($logaction) {
                        echo '<div>操作类型: <strong>' . LOG_MODULE[$search_module]['name'] . ' - ' . LOG_MODULE[$search_module]['action'][$search_action] . '</strong><span class="badge bg-red" onclick="filter_go(\'logaction\');">X</span></div>';
                    }
                    ?>
                </div>
            <?php } ?>
        </div>

        <div class="box-body">
            <div class="line">
                <form action="log.php" method="get">
                    <button type="button" class="btn btn-default pull-left" id="daterange-btn">
                        <span>请选择时间段</span>
                        <i class="fa fa-caret-down"></i>
                    </button>
                    <div class="pull-left" style="padding:0px 15px; display:inline-block;">
                        开始时间: <input type="text" style="width:100px;display:inline-block;" id="search_start_date" name="start"
                                     class="form-control" readonly value="<?php echo $search_start_day; ?>" />
                    </div>
                    <div class="pull-left" style="padding:0px 15px 0px 0px; display:inline-block;">
                        结束时间: <input type="text" style="width:100px;display:inline-block;" name="end" id="search_end_date" class="form-control"
                                     value="<?php echo $search_end_day; ?>" readonly />
                    </div>
                    <div class="pull-left" style="padding:0px 15px; display:inline-block;line-height:32px;">
                        <div class="pull-left">执行账号:&nbsp;&nbsp;</div>
                        <select class="form-control" name="account" style="display:inline !important;float:left;width:auto;">
                            <option value=""></option>
                            <?php foreach($op_user as $ui => $un) { ?><option <?php if($account==$ui) echo ' selected '; ?> value="<?php echo $ui; ?>"><?php echo $un; ?></option><?php } ?>
                        </select>
                    </div>
                    <div class="pull-left" style="padding:0px 15px; display:inline-block;line-height:32px;">
                        <div class="pull-left">操作类型:&nbsp;&nbsp;</div>
                        <select class="form-control" name="logaction" style="display:inline !important;float:left;width:auto;">
                            <option value=""></option>
                            <?php
                            foreach(LOG_MODULE as $_module => $_minfo) {
                                $mname = $_minfo['name'];
                                echo '<optgroup label="'.$mname.'">';
                                foreach($_minfo['action'] as $_akey => $_action) {
                                    ?>
                                    <option <?php if($search_module == $_module && $search_action == $_akey) echo ' selected '; ?> value="<?php echo $_module.':'.$_akey; ?>"><?php echo $_action; ?></option>
                                    <?php
                                }
                                echo '</optgroup>';
                            }
                            ?>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary pull-left">查看数据</button>
                </form>
            </div>
        </div>
    </div>

    <div class="box box-primary">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-search"></i> 兑换记录</h3>
        </div>

        <div class="box-body" id="vbody">

            <table id="logtable" class="table table-bordered table-striped dataTable table-hover " role="grid" aria-describedby="example1_info">
                <thead>
                <tr>
                    <th class="" rowspan="1" colspan="1" width="50" style="text-align:center">ID</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center;">商品批次号</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center;">花费星星</th>
                    <th class="" rowspan="1" colspan="1" width="150">名称</th>
                    <th class="" rowspan="1" colspan="1" width="150" style="text-align:center">兑换时间</th>
                    <th class="" rowspan="1" colspan="1" width="90" style="text-align:center">用户ID</th>
                    <th class="" rowspan="1" colspan="1" width="50" style="text-align:center">头像</th>
                    <th class="" rowspan="1" colspan="1" width="60" style="text-align:center">类型</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">收件人</th>
                    <th class="" rowspan="1" colspan="1" width="90" style="text-align:center">电话</th>
                    <th class="" rowspan="1" colspan="1" width="120" style="text-align:center">省市区</th>
                    <th class="" rowspan="1" colspan="1" width="250" style="text-align:center">详细地址</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">是否发货</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">物流公司</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">物流单号</th>
                    <th class="" rowspan="1" colspan="1" style="text-align:center">操作</th>
                </tr>
                </thead>
                <tbody>
                <?php if(!empty($all_records)) { foreach($all_records as $record) { ?>
                    <tr role="row" style="text-align:center;">
                        <td class="item_id"><?php echo $record['id']; ?></td>
                        <td class="item_productId"><?php echo $record['productId']; ?></td>
                        <td class="item_name"><?php echo $record['needStar']; ?></td>
                        <td class="item_name"><?php echo $record['name']; ?></td>
                        <td class="item_desc" style="font-size:12px;"><?php echo date('Y-m-d H:i:s', $record['time']); ?></td>
                        <td class="item_needStar"><?php echo $record['userId']; ?></td>
                        <td class="item_price"><img src="<?php echo $record['avatar']; ?>" width="30" height="30" /></td>
                        <td class="item_needStar"><?php echo $record['type']==='0' ? '实物' : '虚拟'; ?></td>
                        <td class="item_needStar"><?php echo $record['nickname']; ?></td>
                        <td class="item_needStar"><?php echo $record['phoneNumber']; ?></td>
                        <td class="item_needStar"><?php echo $record['address']; ?></td>
                        <td class="item_needStar"><?php echo $record['detailAddr']; ?></td>
                        <td class="item_needStar"><?php echo $record['status'] === '1' ? '已发货' : '未发货'; ?></td>
                        <td class="item_logistics" data-id="<?php echo $record['logistics'] ?>"><?php echo $logistics[$record['logistics']]; ?></td>
                        <td class="item_logistics_num"><?php echo $record['logistics_num']; ?></td>
                        <td >
                            <?php if ($record['type']==='0'){ ?>
                            <?php if($record['status'] === '0') { ?>
                                <button type="button" class="btn btn-sm btn-success goods" iid="<?php echo $record['id']; ?>">发货</button>
                            <?php }else{ ?>
                                <button type="button" class="btn btn-sm btn-primary goods_edit" iid="<?php echo $record['id']; ?>">修改发货信息</button>
                            <?php } ?>
                            <?php } ?>
                        </td>
                    </tr>
                <?php } } ?>
                </tbody>
            </table>

            <!-- 添加发货信息 -->
            <div class="modal fade" id="modal-add-admin">
                <div class="modal-dialog modal-lg">
                    <form id="item_form" action="exchange_record.php?action=delivery" method="post">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title"></h4>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" id="record_id" name="record_id" value="" />
                                <input type="hidden" id="new_method" name="method" value="" />
                                <table border="0" width="100%" class="modal_table_style">
                                    <tr height="45">
                                        <th width="150" style="text-align:right;padding-right:10px;">物流公司:</th>
                                        <td>
                                            <select class="form-control" id="logistics" name="logistics" style="width:100%;">
                                                <?php foreach($logistics as $k => $v) : ?>
                                                    <option value="<?php echo $k; ?>"><?php echo $k . ' - ' . $v; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">物流单号:</th>
                                        <td><input type="text" class="form-control" size="20" name="logistics_num" id="logistics_num" /></td>
                                    </tr>
                                </table>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary submit_form">确定</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

        </div>

    </div>
</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/jquery.pjax.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
<!-- date-range-picker -->
<script src="bower_components/moment/min/moment.min.js"></script>
<script src="bower_components/bootstrap-daterangepicker/daterangepicker.js"></script>
<!-- bootstrap datepicker -->
<script src="bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
<!-- bootstrap time picker -->
<script src="plugins/timepicker/bootstrap-timepicker.min.js"></script>
<!-- SlimScroll -->
<script src="bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- iCheck 1.0.1 -->
<script src="plugins/iCheck/icheck.min.js"></script>
<!-- FastClick -->
<script src="bower_components/fastclick/lib/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>

<script type="text/javascript">
    function filter_go(filter) {
        var href = window.location.href;
        var href_arr = href.split('?');
        if(!href_arr[1]) {
            return false;
        }
        var args_list = href_arr[1].split('&');
        var new_args = [];
        for(k in args_list) {
            var arg_arr = args_list[k].split('=');
            if(filter == 'time' && (arg_arr[0] == 'start' || arg_arr[0] == 'end')) continue;
            else if(filter == 'logaction' && arg_arr[0] == 'logaction') continue;
            else if(arg_arr[1] == '') continue;
            else if(arg_arr[0] == 'page') continue;
            else new_args.push(args_list[k]);
        }
        var new_arg_str = new_args.join('&');
        if(new_arg_str.length > 0) var new_url = href_arr[0] + '?' + new_arg_str;
        else var new_url = href_arr[0];
        location.href = new_url;
    }

    $(function() {
        var locale = {
            "format": 'YYYY-MM-DD',
            "separator": " -222 ",
            "applyLabel": "确定",
            "cancelLabel": "取消",
            "fromLabel": "起始时间",
            "toLabel": "结束时间'",
            "customRangeLabel": "自定义",
            "weekLabel": "W",
            "daysOfWeek": ["日", "一", "二", "三", "四", "五", "六"],
            "monthNames": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            "firstDay": 1
        };

        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass   : 'iradio_minimal-blue'
        })
        //Red color scheme for iCheck
        $('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
            checkboxClass: 'icheckbox_minimal-red',
            radioClass   : 'iradio_minimal-red'
        })
        $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
            checkboxClass: 'icheckbox_flat-green',
            radioClass   : 'iradio_flat-green'
        });

        $('#daterange-btn').daterangepicker(
            {
                locale   : locale,
                ranges   : {
                    '今日'       : [moment(), moment()],
                    '昨日'   : [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    '最近7日' : [moment().subtract(6, 'days'), moment()],
                    '本月'  : [moment().startOf('month'), moment().endOf('month')],
                    '上月'  : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    '近3个月'  : [moment().subtract(2, 'month').startOf('month'), moment().endOf('month')],
                    '今年'  : [moment().startOf('year'), moment().endOf('year')]
                },
                startDate: '<?php echo $search_start_day; ?>',
                endDate  : '<?php echo $search_end_day; ?>'
            },
            function (start, end) {
                $('#search_start_date').val(start.format('YYYY-MM-DD'));
                $('#search_end_date').val(end.format('YYYY-MM-DD'));
            }
        );

        $('input[name="start"]').daterangepicker({
            locale: locale,
            singleDatePicker: true,
            showDropdowns: true,
            minYear: 1901,
            maxYear: parseInt(moment().format('YYYY'),10)
        }, function(start) {
            //$('#search_start_date').val(start.format('YYYY-MM-DD'));
        });

        $('input[name="end"]').daterangepicker({
            locale: locale,
            singleDatePicker: true,
            showDropdowns: true,
            minYear: 1901,
            maxYear: parseInt(moment().format('YYYY'),10)
        }, function(end) {
            //$('#search_end_date').val(end.format('YYYY-MM-DD'));
        });

        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);

        $('.goods').click(function() {
            var iid = $(this).attr('iid');
            $('#new_method').val('new');
            $('#record_id').val(iid);
            $('#logistics_num').val('');
            $('#modal-add-admin').modal({
                backdrop: 'static',
            });
        });

        $('.goods_edit').click(function() {
            var iid = $(this).attr('iid');
            $('#new_method').val('edit');
            var logistics = $(this).parent().parent().find('.item_logistics').attr('data-id');
            var logistics_num = $(this).parent().parent().find('.item_logistics_num').text();
            $("#logistics option").each(function() {
                if($(this).val() == logistics) {
                    $(this).attr('selected', true);
                }
            });
            $('#logistics_num').val(logistics_num);
            $('#record_id').val(iid);
            $('#modal-add-admin').modal({
                backdrop: 'static',
            });
        });

        $('.submit_form').click(function() {
            $('#item_form').submit();
        });
    });
</script>

</body>
</html>
